﻿<?php
if (!defined('BASEPATH'))
	exit('No direct script access allowed');

class Land extends CI_Controller {
	var $data = array();

	public function __construct() {
		parent::__construct();

		$this -> output -> cache(0);
		$this -> data['current_module'] = site_url("land");
		$this -> data['css_url'] = base_url() . 'css/';
		$this -> data['javscript_url'] = base_url() . 'script/';
		$this -> data['img_url'] = base_url() . 'images/';
		$this -> load -> model('color');
		$this -> data['nowmenu'] = "land";
		$this -> data['title'] = "land";
		$this -> data['role_id']=$this -> session -> userdata('role_id');
	}

	public function land_main() {
		$this -> load -> view('land/land', $this -> data);
	}

	public function get_owner_lst() {
		$query = $this -> db -> query("SELECT * FROM  `vendor`");
		$tmp = json_encode($query -> result_array());
		echo $tmp;

	}

	public function land_all() {
		// ,105.357529
		$this -> data['current_lat'] = "15.298827";
		$this -> data['current_lng'] = "105.357529";

		$query2 = $this -> db -> query('SELECT * FROM land ');

		//14.028, 100.657
		$colorPolygon = "00005A";
		foreach ($query2->result() as $rowLand) {
			$count = 0;
			$javaScipt = "";
			$START_RED = 0;
			$START_GREEN = 0;
			$START_BLUE = 90;
			$queryPolygon = $this -> db -> query("SELECT * FROM land_polygon_map where LAND_ID=" . $rowLand -> landid);
			$tmpString = "var paths" . $count . " =[";
			foreach ($queryPolygon->result() as $rowPolygon) {
				$tmpString .= "new google.maps.LatLng(" . $rowPolygon -> Lat . "," . $rowPolygon -> Log . "),";
			}
			$queryPolygon -> free_result();
			$tmpString .= "];";

			$hexColor = $this -> color -> rgb2html($START_RED, $START_GREEN, $START_BLUE);
			$START_BLUE = $START_BLUE + 10;
			$hexColor = "#" . $colorPolygon;
			//	$hexColor="#ff0000";
			$tmpString .= "var shape" . $count . " = new google.maps.Polygon({
		paths :paths" . $count . ",
		strokeColor : '" . $hexColor . "',
		strokeOpacity : 0.8,
		strokeWeight : 2,
		fillColor : '" . $hexColor . "',
		fillOpacity : 0.35
		});
		google.maps.event.addListener(shape" . $count . ", 'click', function() {
		
		
		});
		shape" . $count . ".setMap(map);";

			$javaScipt .= $tmpString;
		}
		$this -> data['map_script'] = $javaScipt;
		$this -> load -> view('land/land_by_all', $this -> data);
	}

	public function land_by_type() {

		$this -> load -> view('land/land_by_type', $this -> data);
	}

	public function land_by_result() {
		$this -> load -> view('land/land_by_result', $this -> data);
	}

	public function land_by_owner() {
		$this -> load -> view('land/land_by_owner', $this -> data);
	}

	public function land_by_owner_type() {
		$query = $this -> db -> query('SELECT landtypeid,name FROM  `landtype` ');
		$landType = "";
		foreach ($query->result() as $row) {
			$landType .= '<input type="checkbox" name="landtypeid" id="landtypeid" value="' . $row -> landtypeid . '" checked />' . $row -> name . "<br/>";

		}
		$this -> data['landType'] = $landType;
		$this -> load -> view('land/land_owner_type', $this -> data);
	}

	public function getland_owner() {
		$query = $this -> db -> query('SELECT
    `land`.`landid`
    , `land`.`name`
    , `landtype`.`name` AS `land_type`
,`land_polygon`.Size,`vendor`.vfirstname,`vendor`.vlastname,amphur.AMPHUR_NAME,district.DISTRICT_NAME
,province.PROVINCE_NAM,land_address.housenum
FROM
    `land`
    INNER JOIN `landtype` 
        ON (`land`.`landtypeid` = `landtype`.`landtypeid`)
    INNER JOIN `land_address` 
        ON (`land`.`land_addressid` = `land_address`.`land_addressid`)
  INNER JOIN land_polygon
        ON (`land`.`land_polygonid` = `land_polygon`.`land_polygonid`)
INNER JOIN land_owner
        ON (`land`.`landid` = `land_owner`.`landid`)
INNER JOIN vendor
        ON (`land_owner`.`uuid` = `vendor`.`uuid`) 
INNER JOIN vendor_address
        ON (`vendor`.`uuid` =  vendor_address.`uuid`) 

INNER JOIN province
        ON (`vendor_address`.`province` =province.PROVINCE_ID) 

INNER JOIN district
        ON (`vendor_address`.`district` =district.DISTRICT_ID) 
INNER JOIN amphur
        ON (`vendor_address`.`city` =amphur.AMPHUR_ID) 
		 where  `land`.`landid`=' . $_REQUEST['landid']);
		// echo json_encode($query -> result_array());
		$htmlResult = "<table class=\"listing\" cellpadding=\"0\" cellspacing=\"0\">
				<tr>
					<th >No</th>
					<th >ชื่อเกษตรกร</th>
					<th >ประเภท</th>
					<th >ปีที่สมัคร</th>
					<th >จังหวัด</th>
					<th >อําเภอ</th>
				
					<th >หมู่บ้าน</th>
					<th >พื้นที่ (ไร่)</th>
					<th >ผลผลิตต่อไร่</th>
				</tr>";
		foreach ($query->result() as $row) {
			$htmlResult .= "<tr>";
			$htmlResult .= "<td>" . $row -> landid . "</td>";
			$htmlResult .= "<td>" . $row -> vfirstname . "  " . $row -> vlastname . "</td>";
			$htmlResult .= "<td>" . $row -> land_type . "</td>";
			$htmlResult .= "<td></td>";
			$htmlResult .= "<td>" . $row -> PROVINCE_NAME . "</td>";
			$htmlResult .= "<td>" . $row -> AMPHUR_NAME . "</td>";
			$htmlResult .= "<td>" . $row -> housenum . "</td>";

			$htmlResult .= "<td>" . $row -> Size . "</td>";
			$htmlResult .= "<td></td>";
			$htmlResult .= "</tr>";
		}
		echo $htmlResult . "</table>";

	}

	public function land_supply() {
		$this -> load -> view('land/land_supply', $this -> data);
	}

	public function land_by_area() {
		$this -> load -> view('land/land_by_area', $this -> data);
	}

	public function getlandtype() {
		$query = $this -> db -> query("SELECT * FROM  `landtype`");
		$tmp = json_encode($query -> result_array());
		echo $tmp;
	}

	public function map_fillter_owner_type($landtypeid = 0) {
		//echo $landtypeid;

		if ($landtypeid != 0) {
			$landtypeid = str_replace("aaa", ",", $landtypeid);
			if (strlen($landtypeid) > 1) {
				$landtypeid = substr($landtypeid, 0, strlen($landtypeid) - 1);
			}

			$query2 = $this -> db -> query('select land.landid
			,land.name,landtype.name,hexcolor,land.Lat,land.Lng FROM land 
			INNER JOIN landtype ON  landtype.landtypeid=land.landtypeid
			where land.landtypeid in (' . $landtypeid . ")");

		} else {
			$query2 = $this -> db -> query('select land.landid
		,land.name,landtype.name,hexcolor,land.Lat,land.Lng FROM land 
		INNER JOIN landtype ON  landtype.landtypeid=land.landtypeid');
		}
		$flagFirst = TRUE;
		$count = 0;
		$javaScipt = "";
		foreach ($query2->result() as $row) {
			if ($flagFirst == TRUE) {
				$this -> data['current_lat'] = $row -> Lat;
				$this -> data['current_lng'] = $row -> Lng;
				$flagFirst = FALSE;
			}

			$queryPolygon = $this -> db -> query("SELECT * FROM land_polygon_map where LAND_ID=" . $row -> landid);
			$tmpString = "var paths" . $count . " =[";
			foreach ($queryPolygon->result() as $rowPolygon) {
				$tmpString .= "new google.maps.LatLng(" . $rowPolygon -> Lat . "," . $rowPolygon -> Log . "),";
			}
			$queryPolygon -> free_result();
			$tmpString .= "];";

			$hexColor = "#" . $row -> hexcolor;

			$tmpString .= "var shape" . $count . " = new google.maps.Polygon({
					paths :paths" . $count . ",
					strokeColor : '" . $hexColor . "',
					strokeOpacity : 0.8,
					strokeWeight : 2,
					fillColor : '" . $hexColor . "',
					fillOpacity : 0.35
				});
				 google.maps.event.addListener(shape" . $count . ", 'click', function() {
				 	
					getLandDetail(" . $row -> landid . ");
				});
				shape" . $count . ".setMap(map);";
			$count = $count + 1;
			$javaScipt .= $tmpString;
		}
		$this -> data['map_script'] = $javaScipt;
		$this -> load -> view('land/map_full', $this -> data);
	}

	public function map($landid) {
		$query2 = $this -> db -> query('SELECT Lat,Lng FROM land where landid=' . $landid);

		$row = $query2 -> row();
		//14.028, 100.657
		$colorPolygon = "";
		if ($query2 -> num_rows() > 0) {

			$this -> data['current_lat'] = $row -> Lat;
			$this -> data['current_lng'] = $row -> Lng;
		} else {
			$colorPolygon = "00005A";
			$this -> data['current_lat'] = "14.028";
			$this -> data['current_lng'] = "100.657";
		}
		$count = 0;
		$javaScipt = "";
		$START_RED = 0;
		$START_GREEN = 0;
		$START_BLUE = 90;
		$queryPolygon = $this -> db -> query("SELECT * FROM land_polygon_map where LAND_ID=" . $landid);
		$tmpString = "var paths" . $count . " =[";
		foreach ($queryPolygon->result() as $rowPolygon) {
			$tmpString .= "new google.maps.LatLng(" . $rowPolygon -> Lat . "," . $rowPolygon -> Log . "),";
		}
		$queryPolygon -> free_result();
		$tmpString .= "];";

		$hexColor = $this -> color -> rgb2html($START_RED, $START_GREEN, $START_BLUE);
		$START_BLUE = $START_BLUE + 10;
		$hexColor = "#" . $colorPolygon;
		//	$hexColor="#ff0000";
		$tmpString .= "var shape" . $count . " = new google.maps.Polygon({
					paths :paths" . $count . ",
					strokeColor : '" . $hexColor . "',
					strokeOpacity : 0.8,
					strokeWeight : 2,
					fillColor : '" . $hexColor . "',
					fillOpacity : 0.35
				});
				 google.maps.event.addListener(shape" . $count . ", 'click', function() {
				 	
	
				});
				shape" . $count . ".setMap(map);";

		$javaScipt .= $tmpString;
		$this -> data['map_script'] = $javaScipt;
		$this -> load -> view('land/map', $this -> data);
	}

	public function index() {

		$this -> load -> view('land/land', $this -> data);
	}

	public function getlandall() {
		$reul = "";

		$query = $this -> db -> query("SELECT
			    `land`.`landid`
			    , `land`.`name` AS `land_name`
			    , `landtype`.`hexcolor`, `landtype`.`name` as landType
			    , `land`.`Lat`, `land`.`Lng`
				FROM
				    `land`
				    INNER JOIN `landtype` 
        ON (`land`.`landtypeid` = `landtype`.`landtypeid`)");
		$resultArray = array();

		foreach ($query->result() as $row) {

			$resultJson = array();
			$resultJson['landid'][] = sprintf("%06d", $row -> landid);
			$resultJson['landcolor'][] = "#" . $row -> hexcolor;
			$resultJson['landname'][] = $row -> land_name;
			$resultJson['landtype'][] = $row -> landType;
			$resultJson['Lat'][] = $row -> Lat;
			$resultJson['Lng'][] = $row -> Lng;
			$queryPolygon = $this -> db -> query("SELECT * FROM land_polygon_map where LAND_ID=" . $row -> landid);

			$arrayTmp = array();
			foreach ($queryPolygon->result() as $rowPolygon) {
				$arrayTmp[] = $rowPolygon -> Lat . "," . $rowPolygon -> Log;
				// $LatTmp[]=$rowPolygon -> Lat;
				// $LngTmp[]=$rowPolygon -> Log;
			}
			$resultJson['polygon'][] = $arrayTmp;
			//	$resultArray['lanlst'][] = $resultJson;
			$resultArray[] = $resultJson;
		}

		echo json_encode($resultArray);
	}

	public function getland_by_type() {
		$reul = "";
		$resultArray = array();
		if ($_REQUEST['landtype'] != "") {
			$query = $this -> db -> query("SELECT
			    `land`.`landid`
			    , `land`.`name` AS `land_name`
			    , `landtype`.`hexcolor`, `landtype`.`name` as landType
			    , `land`.`Lat`, `land`.`Lng`
				FROM
				    `land`
				    INNER JOIN `landtype` 
        ON (`land`.`landtypeid` = `landtype`.`landtypeid`) where `land`.landtypeid in (" . $_REQUEST['landtype'] . ")");

			foreach ($query->result() as $row) {

				$resultJson = array();
				$resultJson['landid'][] = sprintf("%06d", $row -> landid);
				$resultJson['landcolor'][] = "#" . $row -> hexcolor;
				$resultJson['landname'][] = $row -> land_name;
				$resultJson['landtype'][] = $row -> landType;
				$resultJson['Lat'][] = $row -> Lat;
				$resultJson['Lng'][] = $row -> Lng;
				$queryPolygon = $this -> db -> query("SELECT * FROM land_polygon_map where LAND_ID=" . $row -> landid);

				$arrayTmp = array();
				foreach ($queryPolygon->result() as $rowPolygon) {
					$arrayTmp[] = $rowPolygon -> Lat . "," . $rowPolygon -> Log;
					// $LatTmp[]=$rowPolygon -> Lat;
					// $LngTmp[]=$rowPolygon -> Log;
				}
				$resultJson['polygon'][] = $arrayTmp;
				//	$resultArray['lanlst'][] = $resultJson;
				$resultArray[] = $resultJson;
			}

		}
		echo json_encode($resultArray);
	}

	public function get_ownerall() {
		$reul = "";
		$resultArray = array();

		$query = $this -> db -> query("SELECT
    `land`.`landid`
    , `land`.`name` AS `land_name`
    , `land`.`Lat`
    , `land`.`Lng`
    , `vendor`.`vfirstname`
    , `vendor`.`vlastname`
FROM
    `ube`.`land_owner`
    INNER JOIN `ube`.`land` 
        ON (`land_owner`.`landid` = `land`.`landid`)
    INNER JOIN `ube`.`vendor` 
        ON (`vendor`.`uuid` = `land_owner`.`uuid`) ");

		foreach ($query->result() as $row) {

			$resultJson = array();
			$resultJson['landid'][] = sprintf("%06d", $row -> landid);
			$resultJson['landname'][] = $row -> land_name;
			$resultJson['Lat'][] = $row -> Lat;
			$resultJson['Lng'][] = $row -> Lng;

			$resultArray[] = $resultJson;
		}

		echo json_encode($resultArray);
	}

	public function get_owner_fillter() {
		$reul = "";
		$resultArray = array();
		if ($_REQUEST['ownerid'] != "") {
			$query = $this -> db -> query("SELECT
    `land`.`landid`
    , `land`.`name` AS `land_name`
    , `land`.`Lat`
    , `land`.`Lng`
    , `vendor`.`vfirstname`
    , `vendor`.`vlastname`
FROM
    `ube`.`land_owner`
    INNER JOIN `ube`.`land` 
        ON (`land_owner`.`landid` = `land`.`landid`)
    INNER JOIN `ube`.`vendor` 
        ON (`vendor`.`uuid` = `land_owner`.`uuid`) where `land_owner`.uuid in (" . $_REQUEST['ownerid'] . ")");

			foreach ($query->result() as $row) {

				$resultJson = array();
				$resultJson['landid'][] = sprintf("%06d", $row -> landid);
				$resultJson['landname'][] = $row -> land_name;
				$resultJson['Lat'][] = $row -> Lat;
				$resultJson['Lng'][] = $row -> Lng;

				$resultArray[] = $resultJson;
			}

		}
		echo json_encode($resultArray);
	}

	public function index2() {
		$JsonResult = array();
		$query = $this -> db -> query("SELECT * FROM land order by landid desc");

		foreach ($query->result() as $row) {
			$JsonResult[] = $row -> landid;
			$queryPolygon = $this -> db -> query("SELECT Lat,Log FROM land_polygon_map where LAND_ID=" . $row -> landid);
			foreach ($query->result() as $row) {
			}
			$JsonResult['polygon'][] = $queryPolygon -> result_array();
		}
		echo json_encode($JsonResult);

	}

	public function landupload() {
		$queryV = $this -> db -> query("SELECT  `uuid` , CONCAT(  `vfirstname` ,  '  ',  `vlastname` ) AS full_name FROM  `vendor`");
		$dataVender = array();
		$dataVender[0] = "Select";
		foreach ($queryV->result() as $row) {
			$dataVender[$row -> uuid] = $row -> full_name;
		}

		$this -> data['ownerLand'] = $dataVender;
		$query = $this -> db -> query("SELECT *  FROM  `landtype` ");
		$selectLandtype = "";
		$dataLandType = array();
		$dataLandType[0] = "Select";
		foreach ($query->result() as $row) {
			$dataLandType[$row -> landtypeid] = $row -> name;

		}
		// landtype
		$this -> data['landtype'] = $dataLandType;
		$this -> load -> view('land/land_upload', $this -> data);
	}

	public function get_all_land() {
		$query = $this -> db -> query("SELECT * FROM  `land` ORDER BY  `land`.`landid` asc ");

		$output = " <div class=\"table\"><table width=\"100%\"   class=\"listing\" cellpadding=\"0\" cellspacing=\"0\" >
			<tr>
				<th width=\"30px\"   align=\"center\">ID</th>
				<th  >LandName</th>
				<th width=\"5%\" align=\"center\">Delete</th>
				<th  width=\"5%\" align=\"center\">Edit</th>
			</tr>";
		$imageURL = base_url() . "images/";
		if ($query -> num_rows() > 0) {
			foreach ($query->result() as $row) {
				$output .= "<tr >";
				$output .= "<td  align=\"center\">" . sprintf("%06d", $row -> landid) . "</td>";
				$output .= "<td>" . $row -> name . "</td>";
				$output .= "<td align=\"center\"><a href=\"javascript:deleteLand('" . $row -> landid . "')\">" . "<img src='" . $imageURL . "icon_delete.png'/></a></td>";
				$output .= "<td align=\"center\"><a href=\"javascript:getDataByID('" . $row -> landid . "','" . $row -> landtypeid . "')\">" . "<img src='" . $imageURL . "icon_edit.png'/></a></td>";
				$output .= "</tr>";
			}
		} else {
			$output .= "<tr >";
			$output .= "<td colspan=\"4\" align=\"center\"><br />No Data<br /><br /></td>";
			$output .= "</tr>";
		}
		echo $output . "</table>";
	}

	public function save_address() {

		$data = array('housenum' => $_REQUEST['housenum'], 'village' => $_REQUEST['village'], 'moono' => $_REQUEST['moono'], 'street' => $_REQUEST['street'], 'district' => $_REQUEST['district'], 'city' => $_REQUEST['city'], 'province' => $_REQUEST['province'], 'country' => $_REQUEST['country'], 'zipcode' => $_REQUEST['zipcode']);

		$this -> db -> update('land_address', $data, "land_addressid =" . $_REQUEST['land_docid']);

		if ($_REQUEST['ownerland'] != "0") {
			$query2 = $this -> db -> query('SELECT * FROM land_owner where landid=' . $_REQUEST['landid']);
			$row = $query2 -> row();
			$data = array();
			$data['landid'] = $_REQUEST['landid'];
			$data['uuid'] = $_REQUEST['ownerland'];
			if ($query2 -> num_rows() > 0) {
				$this -> db -> update('land_owner', $data, "ID =" . $row -> ID);

			} else {
				$this -> db -> insert('land_owner', $data);
			}
		}

		//ownerLand
		// $_REQUEST['landtype']
		$this -> db -> update('land', array('landtypeid' => $_REQUEST['landtype'], 'MAP_COLOR' => $_REQUEST['color_map']), "land_addressid =" . $_REQUEST['land_docid']);

		echo "Save Complete";
	}

	public function getAddressByID() {

		$query2 = $this -> db -> query('SELECT * from land_owner where landid=' . $_REQUEST['landid']);

		if ($query2 -> num_rows() > 0) {

			$query = $this -> db -> query("SELECT
			land_owner.uuid,
			land_address.land_addressid,
			land_address.housenum,
			land_address.village,
			land_address.moono,
			land_address.street,
			land_address.district,
			land_address.city,
			land_address.province,
			land_address.country,
			land_address.zipcode,
			land_address.land_docid,
			land.landtypeid,
			land.MAP_COLOR,land.landtypeid
			FROM
			land
			INNER JOIN land_owner ON land_owner.landid = land.landid
			INNER JOIN land_address ON land_address.land_addressid = land.land_addressid  
			 where land_address.land_addressid =" . $_REQUEST['landid']);
		} else {
			$query = $this -> db -> query("SELECT
			land_address.land_addressid,
			land_address.housenum,
			land_address.village,
			land_address.moono,
			land_address.street,
			land_address.district,
			land_address.city,
			land_address.province,
			land_address.country,
			land_address.zipcode,
			land_address.land_docid,
			land.landtypeid,
			land.MAP_COLOR,land.landtypeid
			FROM 
			land_address
			INNER JOIN land ON land_address.land_addressid = land.land_addressid   where land.landid =" . $_REQUEST['landid']);

		}
		$tmp = json_encode($query -> result_array());
		$tmp = str_replace("[", "", $tmp);
		$tmp = str_replace("]", "", $tmp);
		echo $tmp;
	}

	public function getLandInfo() {
		$query = $this -> db -> query("SELECT * FROM  `landcrop_polygon_map` where LAND_ID =" . $_REQUEST['landid']);
		$tmp = json_encode($query -> result_array());
		$tmp = str_replace("[", "", $tmp);
		$tmp = str_replace("]", "", $tmp);
		echo $tmp;

	}

	public function deleteLandArea() {
		//landtypeid	int(11)			Yes	NULL
		// land_addressid	int(11)			Yes	NULL
		// land_polygonid
		$query2 = $this -> db -> query('SELECT land_addressid,land_polygonid FROM land where landid=' . $_REQUEST['landid']);
		$row = $query2 -> row();
		$land_addressid = $row -> land_addressid;
		//	$land_polygonid = $row->land_polygonid;
		$this -> db -> delete('land', array('landid' => $_REQUEST['landid']));
		$this -> db -> delete('landcrop_polygon_map', array('LAND_ID' => $_REQUEST['landid']));
		$this -> db -> delete('land_address', array('land_addressid' => $row -> land_addressid));
		$this -> db -> delete('land_polygon', array('land_polygonid' => $row -> land_polygonid));
		$this -> db -> delete('land_polygon_map', array('LAND_ID' => $_REQUEST['landid']));

		echo "Delete Complete";
	}

	public function geography() {
		$query = $this -> db -> query("SELECT * FROM  `m_geography`");
		$tmp = json_encode($query -> result_array());
		// $tmp = str_replace("[", "", $tmp);
		// $tmp = str_replace("]", "", $tmp);
		echo $tmp;

	}

	public function province() {
		$query = $this -> db -> query("SELECT * FROM  `m_province` where GEO_ID=" . $_REQUEST['geoid']);
		$tmp = json_encode($query -> result_array());
		echo $tmp;
	}

	public function provinceall() {
		$query = $this -> db -> query("SELECT * FROM  `m_province` ");
		$tmp = json_encode($query -> result_array());
		echo $tmp;
	}

	public function amphur() {
		$query = $this -> db -> query("SELECT * FROM  `m_amphur` where PROVINCE_ID=" . $_REQUEST['provinceid']);
		$tmp = json_encode($query -> result_array());
		echo $tmp;
	}

	public function district() {
		$query = $this -> db -> query("SELECT * FROM  `m_district` where AMPHUR_ID=" . $_REQUEST['amphurid']);
		$tmp = json_encode($query -> result_array());
		echo $tmp;
	}

	public function uploadgpx() {

		if (isset($_FILES["uploadfile"]["name"]) && $_FILES["uploadfile"]["name"] != "") {
			$save_tmp = time() . $_FILES["uploadfile"]["name"];
			if (substr($_FILES["uploadfile"]["name"], -4) == ".kml") {

				$saveKMLPath = $_SERVER['DOCUMENT_ROOT'] . "/ci_ube/data/kml/" . $save_tmp;
				if (move_uploaded_file($_FILES["uploadfile"]["tmp_name"], $saveKMLPath)) {

					$data = array('land_file' => $save_tmp);
					$this -> db -> insert('land_doc', $data);
					$landDocID = $this -> db -> insert_id();

					$xml = simplexml_load_file($saveKMLPath);
					$count = 0;

					foreach ($xml->Document->Placemark as $place) {

						$checkHaveInDB = $this -> db -> query("SELECT landid FROM land where name='" . $place -> name . "'");
						$lastInsertID = "";
						$LandID = "";
						$AddressID = "";
						$count = $count + 1;
						$LandName_tm = "";
						if ($checkHaveInDB -> num_rows() > 0) {
							$row = $checkHaveInDB -> row();
							$LandID = $row -> LAND_ID;
							$this -> db -> query("delete from  land_polygon_map where LAND_ID=" . $LandID);
						} else {
							$data = array('name' => "" . $place -> name);
							$LandName_tm = $place -> name;
							foreach ($place->LookAt as $lookAtArea) {
								$data['Lat'] = $lookAtArea -> latitude;
								$data['Lng'] = $lookAtArea -> longitude;

							}

						}
						$dataLandAddress = array('land_docid' => $landDocID);
						$this -> db -> insert('land_address', $dataLandAddress);

						$data['land_addressid'] = $this -> db -> insert_id();
						$this -> db -> insert('land', $data);
						$LandID = $this -> db -> insert_id();
						$tmpPoligon = "";
						$latTmp = "";
						$logtmp = "";
						foreach ($place->Polygon as $areaPolygon) {
							$tmp1 = trim($areaPolygon -> outerBoundaryIs[0] -> LinearRing -> coordinates);
							$tmp1 = str_replace(",0", "#", $tmp1);
							$tmp1 = str_replace(",", " ", $tmp1);
							$tmp1 = str_replace("#", ",", $tmp1);
							$tmp1 = substr($tmp1, 0, strlen($tmp1) - 1);
							$tmp1 = explode(",", $tmp1);
							$tmpPolygon = "";
							for ($i = 0; $i < count($tmp1); $i++) {
								$tmpArray = array();
								$tmpArray = explode(" ", trim($tmp1[$i]));
								for ($j = 0; $j < count($tmpArray); $j = $j + 2) {
									$LatLongTmp = array();
									$LatLongTmp['Log'] = $tmpArray[$j];
									$LatLongTmp['Lat'] = $tmpArray[$j + 1];
									$LatLongTmp['LAND_ID'] = $LandID;
									$this -> db -> insert('land_polygon_map', $LatLongTmp);

									$tmpPolygon = $tmpPolygon . $tmpArray[$j + 1] . " " . $tmpArray[$j] . ",";
								}
								$logtmp = $tmpArray[0];
								$latTmp = $tmpArray[1];
							}
							$tmpPolygon = substr($tmpPolygon, 0, strlen($tmpPolygon) - 1);
							$sqlInsertPoligon = "INSERT INTO land_polygon(`name`,`polygon`) VALUES ('" . $LandName_tm . "', GeomFromText('POLYGON(( " . $tmpPolygon . "))'))";
							$this -> db -> query($sqlInsertPoligon);
							$polygonID = $this -> db -> insert_id();
							$calculateArea = $this -> db -> query("SELECT area(polygon) as areasize FROM  land_polygon where land_polygonid=" . $polygonID);
							$rowResultArea = $calculateArea -> row();

							$areaSize = (($rowResultArea -> areasize / 1000000) / 0.0016);
							//	$this->db->trans_complete();
							$this -> db -> query("update land set land_polygonid=" . $polygonID . ",Lat=" . $latTmp . ",Lng=" . $logtmp . " where landid=" . $LandID);
							//$this -> db -> query("update land set land_polygonid=" . $polygonID . " where landid=" . $LandID);
							$this -> db -> query("update land_polygon set Size=" . $areaSize . " where land_polygonid=" . $polygonID);
							// $this -> db -> update('land',  array('land_polygonid' => $polygonID),"landid=".$LandID);

							//$this -> db -> update('land_polygon', array('Size' => $rowResultArea -> areasize), "land_polygonid=" . $polygonID);
						}

					}
				} else {

				}
			} else {
				$saveKMLPath = $_SERVER['DOCUMENT_ROOT'] . "/ci_ube/data/gpx/" . $save_tmp;
				if (move_uploaded_file($_FILES["uploadfile"]["tmp_name"], $saveKMLPath)) {

					$this -> db -> insert('land_doc', array('land_file' => $save_tmp));
					$landDocID = $this -> db -> insert_id();

					$xml = simplexml_load_file($saveKMLPath);
					$count = 0;
					foreach ($xml -> trk as $place) {

						$checkHaveInDB = $this -> db -> query("SELECT landid,land_polygonid FROM land where name='" . $place -> name . "'");
						$lastInsertID = "";
						$LandID = "";
						$AddressID = "";
						$count = $count + 1;
						$LandName_tm = "";
						$dataLand = array();
						if ($checkHaveInDB -> num_rows() > 0) {
							$row = $checkHaveInDB -> row();
							$LandID = $row -> landid;
							$this -> db -> delete('land_polygon_map', array('LAND_ID' => $LandID));
						} else {

							$dataLand['name'] = "" . $place -> name;
							$LandName_tm = $place -> name;
							if (count($place -> trkseg -> trkpt) > 0) {
								$attrs = $place -> trkseg[0] -> trkpt -> attributes();
								$dataLand['Lat'] = $attrs['lat'];
								$dataLand['Lng'] = $attrs['lon'];
							}
						}

						$dataLandAddress = array('land_docid' => $landDocID);
						$this -> db -> insert('land_address', $dataLandAddress);

						$dataLand['land_addressid'] = $this -> db -> insert_id();
						$this -> db -> insert('land', $dataLand);
						$LandID = $this -> db -> insert_id();

						$tmpPolygonX = "";
						$latTmp = "";
						$logtmp = "";
						foreach ($place -> trkseg->trkpt as $locationRow) {
							$attrs = $locationRow -> attributes();
							$LatLongTmp = array();
							$LatLongTmp['Lat'] = $attrs['lat'];
							$LatLongTmp['Log'] = $attrs['lon'];
							$latTmp = $attrs['lat'];
							$logtmp = $attrs['lon'];
							// $comma_separated = implode(" ", $LatLongTmp);
							// $tmpxxx = trim($attrs['lat']) . " " . trim($attrs['lon']) . ",";
							// $tmpPolygonX .= $tmpxxx;

							$LatLongTmp['LAND_ID'] = $LandID;
							$this -> db -> insert('land_polygon_map', $LatLongTmp);

							// $tmpPoligon .= $comma_separated . ",";
						}

						// $str = substr($tmpPolygonX, 0, strlen($tmpPolygonX) - 1);
						// $sqlInsertPoligon = "INSERT INTO land_polygon(`name`,`polygon`) VALUES ('" . $LandName_tm . "', GeomFromText('POLYGON(( " . $str . "))'))";
						// $this -> db -> query($sqlInsertPoligon);

						// $tmpPolygon = substr($tmpPolygonX, 0, strlen($tmpPolygonX) - 1);
						// $sqlInsertPoligon = "INSERT INTO land_polygon(`name`,`polygon`) VALUES ('" . $LandName_tm . "', GeomFromText('POLYGON(( " . $tmpPolygon . "))'))";
						//	$sqlInsertPoligon = "INSERT INTO land_polygon(`name`,`polygon`) VALUES ('" . $LandName_tm . "', GeomFromText('POLYGON(( " . $tmpPolygon . "))'))";
						// $this -> db -> query($sqlInsertPoligon);
						// echo $sqlInsertPoligon;
						$this -> db -> query("update land set Lat=" . $latTmp . ",Lng=" . $logtmp . " where landid=" . $LandID);
						//	echo $sqlInsertPoligon;
						// $polygonID = $this -> db -> insert_id();
						// $calculateArea = $this -> db -> query("SELECT area(polygon) as areasize FROM  land_polygon where land_polygonid=" . $polygonID);
						//	echo "SELECT area(polygon) as areasize FROM  land_polygon where landcrop_polygonid=" . $polygonID;
						// $rowResultArea = $calculateArea -> row();

						// $areaSize = (($rowResultArea -> areasize / 1000000) / 0.0016);
						//	$this->db->trans_complete();
						// $this -> db -> query("update land set land_polygonid=" . $polygonID . " where landid=" . $LandID);
						// $this -> db -> query("update land_polygon set Size=" . $areaSize . " where landid=" . $polygonID);
						// $this -> db -> update('land',  array('land_polygonid' => $polygonID),"landid=".$LandID);
						// $this -> db -> update('land_polygon', array('Size' => $rowResultArea -> areasize), "landcrop_polygonid =" . $polygonID);
					}
				}
				echo $count;
			}
		}
	}

}
